package com.etone.android.test.utils;

import java.io.File;

import org.apache.commons.io.FileUtils;
import org.junit.Assert;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.android.AndroidDriver;

/**
 * Selenium测试截图工具
 * 
 * @author ZhangQiude
 * 
 */

public class SeleniumCaptureScreenUtils {
	private static final double CAPTURE_TIME_WAIT = 2;
	private AndroidDriver driver;

	public SeleniumCaptureScreenUtils(AndroidDriver driver) {
		super();
		this.driver = driver;
	}

	/**
	 * 正常情况下截图
	 * 
	 * @param dirName
	 * @param photoName
	 */
	public void captureScreen(String dirName, String photoName) {
		try {
			sleep(CAPTURE_TIME_WAIT);
			File srcFile = driver.getScreenshotAs(OutputType.FILE);
			FileUtils.copyFile(srcFile, new File(dirName + File.separator
					+ photoName));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 找不到Element时的截图
	 * 
	 * @param dirName
	 * @param photoName
	 * @param errMsg
	 */
	public void captureScreen(String dirName, String photoName, String errMsg) {
		captureScreen(dirName, photoName);
		logErr(String.format("%s.Snapshot is: %s", errMsg, photoName));
		Assert.assertNotNull(null);
	}

	/**
	 * 打印错误
	 * 
	 * @param str
	 */
	private void logErr(Object str) {
		System.out.println("[  Err  ] " + str.toString());
	}

	/**
	 * 睡眠单位为秒
	 * 
	 * @param seconds
	 */
	private static void sleep(double seconds) {
		try {
			Thread.sleep((long) (seconds * 1000));
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}
